package com.carl.mall.ware.service.impl;

import com.carl.common.constant.WareConstant;
import com.carl.mall.ware.entity.PurchaseDetailEntity;
import com.carl.mall.ware.service.PurchaseDetailService;
import com.carl.mall.ware.service.WareSkuService;
import com.carl.mall.ware.vo.MergeVO;
import com.carl.mall.ware.vo.PurchaseDoneVO;
import com.carl.mall.ware.vo.PurchaseItemDoneVO;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.carl.common.utils.PageUtils;
import com.carl.common.utils.Query;

import com.carl.mall.ware.dao.PurchaseDao;
import com.carl.mall.ware.entity.PurchaseEntity;
import com.carl.mall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {


    @Autowired
    private PurchaseDetailService purchaseDetailService;

    @Autowired
    private WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageByUnreceive(Map<String, Object> params) {

        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>().eq("status",0).or().eq("status",1)
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public Integer saveMerge(MergeVO mergeVO) {
        //1.没有采购单则新建一个采购单进行合并
        //2.有采购单则新建到这个采购单
        Long purchaseId = mergeVO.getPurchaseId();
        if (purchaseId == null) {
            //采购单
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());
            this.save(purchaseEntity);
            purchaseId = purchaseEntity.getId();
        }
        //判断采购单的状态 只能是新建或者已分配才能合并，如果是已领取 就不能再合并
        PurchaseEntity purchaseEntity = this.getById(purchaseId);
        if (purchaseEntity.getStatus()  > WareConstant.PurchaseStatusEnum.RECEIVE.getCode()){
            // 该菜单不能合并
            return -1;
        }
        //整合采购需求单
        List<Long> items = mergeVO.getItems();
        final Long purchaseFinalId = purchaseId;
        List<PurchaseDetailEntity> detailEntityList = items.stream().map((item) -> {
            PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
            detailEntity.setId(item);
            detailEntity.setPurchaseId(purchaseFinalId);
            detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGED.getCode());
            return detailEntity;
        }).filter(id ->{
            PurchaseDetailEntity detailEntity = purchaseDetailService.getById(id);
            if (detailEntity.getStatus() == WareConstant.PurchaseDetailStatusEnum.ASSIGED.getCode() ||
                    detailEntity.getStatus() == WareConstant.PurchaseDetailStatusEnum.CREATED.getCode()){
                return true;
            }
            return false;
        }).collect(Collectors.toList());
        if (!detailEntityList.isEmpty()){
            purchaseDetailService.updateBatchById(detailEntityList);
        }
        PurchaseEntity entity = new PurchaseEntity();
        entity.setUpdateTime(new Date());
        entity.setId(purchaseId);
        this.updateById(entity);
        return 1;

    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<PurchaseEntity> wrapper = new QueryWrapper<>();
        String status = (String) params.get("status");
        if (!StringUtils.isEmpty(status)){
            wrapper.eq("status",status);
        }
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)){
            wrapper.and((wrappers) ->{
                wrappers.eq("assignee_id",key).or().eq("phone",key)
                        .or().like("assignee_name",key)
                        .or().eq("priority",key)
                        .or().eq("ware_id",key);
            });
        }

        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                wrapper
        );
        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void received(List<Long> ids) {
         //1. 领取的采购单状态只能是新建或者已分配的采购单  其他的是不能领取的
        if (!ids.isEmpty()){
            List<PurchaseEntity> purchaseEntities = this.listByIds(ids);
            for (PurchaseEntity purchaseEntity : purchaseEntities) {
                Long purchaseEntityId = purchaseEntity.getId();
                List<PurchaseDetailEntity> detailEntities = purchaseDetailService
                        .list(new QueryWrapper<PurchaseDetailEntity>()
                                .eq("purchase_id", purchaseEntityId));
                if ((purchaseEntity.getStatus() == WareConstant.PurchaseStatusEnum.CREATED.getCode()
                        || purchaseEntity.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGED.getCode())&& !detailEntities.isEmpty()){
                    //2. 更新采购单的状态为  已领取
                    PurchaseEntity purchaseEntity1 = new PurchaseEntity();
                    purchaseEntity1.setId(purchaseEntity.getId());
                    purchaseEntity1.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());
                    purchaseEntity1.setUpdateTime(new Date());
                    this.updateById(purchaseEntity1);
                    //3. 更新采购项的状态 为正在采购
                    //根据采购单获取对应的采购项
                    for (PurchaseDetailEntity detailEntity : detailEntities) {
                        PurchaseDetailEntity detailEntity1 = new PurchaseDetailEntity();
                        detailEntity1.setId(detailEntity.getId());
                        detailEntity1.setStatus(WareConstant.PurchaseDetailStatusEnum.BUYING.getCode());
                        purchaseDetailService.updateById(detailEntity1);
                    }
                }

            }
        }

    }
    /**
     * 完成采购
     * {
     *     id ： 1 采购单
     *     items：[
     *     {itemId : 1,status: 4,reason: ""},
     *      {itemId : 2,status: 4,reason: ""}
     *     ] //采购项
     * }
     */
    @Transactional
    @Override
    public void done(PurchaseDoneVO purchaseDoneVO) {
        //1.获取采购单id
        Long id = purchaseDoneVO.getId(); //获取采购单id
        //标识符
        boolean flag = true;
        //获取所有采购需求
        List<PurchaseItemDoneVO> purchaseDoneVOItems = purchaseDoneVO.getItems();
        List<PurchaseDetailEntity> purchaseDetailEntityList = new ArrayList<>();
        for (PurchaseItemDoneVO purchaseDoneVOItem : purchaseDoneVOItems) {
              PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
              if (purchaseDoneVOItem.getStatus() == WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode()){
                  //如果有异常则把标识符制成false
                  flag = false;
                  purchaseDetailEntity.setStatus(purchaseDoneVOItem.getStatus());
              }else {
                  //采购项的状态是成功的
                  purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.FINISH.getCode());
                  //然后将成功的进行入库操作 通过采购需求的id查出具体的采购需求
                  PurchaseDetailEntity detailEntity = purchaseDetailService.getById(purchaseDoneVOItem.getItemId());
                  wareSkuService.addStock(detailEntity.getSkuId(),detailEntity.getWareId(),detailEntity.getSkuNum());
              }
              purchaseDetailEntity.setId(purchaseDoneVOItem.getItemId()); //这里设置id是为了方便全量更新
              purchaseDetailEntityList.add(purchaseDetailEntity);
              purchaseDetailService.updateBatchById(purchaseDetailEntityList);

        }

        //改变采购单的状态
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(id);
        purchaseEntity.setStatus(flag?WareConstant.PurchaseStatusEnum.FINISH.getCode()
                :WareConstant.PurchaseStatusEnum.HASERROR.getCode());
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);



    }


}